﻿using Client.Framework;
using UnityEngine;

/// <summary>
/// 控件刷新回调
/// </summary>
/// <param name="go"></param>
/// <param name="idx"></param>
public delegate void ItemCallBack(GameObject go, int idx);

[DisallowMultipleComponent]
public class MyPageTurn : MonoBehaviour
{
    [SerializeField]
    private MyGoToPage NumChoose;
    ItemCallBack OnItemChange;

    private int m_MaxGoNum = 1;
    private int m_ItemGoNum = 1;

    public int CurPageNum { get; private set; }
    public int MaxPageNum { get; private set; }

    void Awake()
    {
        if (NumChoose != null) { NumChoose.OnChange = SetCurPage; }
    }

    void OnDestroy()
    {
        if (NumChoose != null) { NumChoose.OnChange = null; }
    }

    /// <summary>
    /// 刷新数据
    /// </summary>
    /// <param name="maxNum"></param>
    /// <param name="curPage"></param>
    public void RefreshData(int maxNum, int curPage = 1)
    {
        m_MaxGoNum = maxNum; CurPageNum = curPage;
        m_ItemGoNum = transform.childCount;
        MaxPageNum = m_MaxGoNum / m_ItemGoNum;

        if (m_MaxGoNum % m_ItemGoNum > 0)
        {
            MaxPageNum += 1;
        }

        if (MaxPageNum <= 0)
        {
            MaxPageNum = 1;
        }
        if (CurPageNum > MaxPageNum)
        {
            CurPageNum = 1;
        }

        if (NumChoose != null)
        {
            NumChoose.SetData(CurPageNum, MaxPageNum);
        }
        SetCurPage(CurPageNum);
    }

    /// <summary>
    /// 设置当前页签数据
    /// </summary>
    /// <param name="curPage"></param>
    public void SetCurPage(int curPage)
    {
        CurPageNum = curPage;
        int beginIdx = (curPage - 1) * m_ItemGoNum;
        int endIdx = beginIdx + m_ItemGoNum;
        if (endIdx > m_MaxGoNum) { endIdx = m_MaxGoNum; }

        for (int i = 0; i < m_ItemGoNum; i++)
        {
            var tf = transform.GetChild(i);
            int idx = beginIdx + i;

            Utility.SetActive(tf, idx < endIdx);
            if (tf != null && idx < endIdx)
            {
                OnItemChange?.Invoke(tf.gameObject, idx);
            }
        }

        if (NumChoose != null)
        {
            NumChoose.CurValue = CurPageNum;
        }
    }
}